import numpy as np
import matplotlib.pyplot as plt

# 中文和负号的正常显示
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False

def recursive_sequence(n_terms):
    """
    计算递归定义的数列: a_{n+1} = sqrt(2 + a_n), a_1 = sqrt(2)
    """
    sequence = [np.sqrt(2)]  # a1
    for i in range(1, n_terms):
        next_term = np.sqrt(2 + sequence[-1])
        sequence.append(next_term)
    return sequence

# 计算前20项
n_terms = 20
sequence = recursive_sequence(n_terms)

# 绘制数列收敛情况
plt.figure(figsize=(12, 5))

plt.subplot(1, 2, 1)
plt.plot(range(1, n_terms+1), sequence, 'bo-', markersize=4)
plt.axhline(y=2, color='r', linestyle='--', label='极限值: 2')
plt.xlabel('n')
plt.ylabel('a_n')
plt.title('单调有界数列收敛示例')
plt.legend()
plt.grid(True, alpha=0.3)

# 计算误差（与极限值的差）
errors = [2 - term for term in sequence]

plt.subplot(1, 2, 2)
plt.semilogy(range(1, n_terms+1), errors, 'ro-', markersize=4)
plt.xlabel('n')
plt.ylabel('误差 (2 - a_n)')
plt.title('误差收敛情况（对数坐标）')
plt.grid(True, alpha=0.3)

plt.tight_layout()
plt.show()

# 输出前几项和最后几项
print("数列前10项:")
for i in range(min(10, n_terms)):
    print(f"a_{i+1} = {sequence[i]:.10f}")

print("\n数列最后5项:")
for i in range(max(0, n_terms-5), n_terms):
    print(f"a_{i+1} = {sequence[i]:.10f}")

# 验证单调性和有界性
is_increasing = all(sequence[i] <= sequence[i+1] for i in range(len(sequence)-1))
is_bounded = all(term < 2 for term in sequence)

print(f"\n数列单调递增: {is_increasing}")
print(f"数列有上界(所有项 < 2): {is_bounded}")
print(f"极限值: {sequence[-1]:.10f}")